package com.njupt.sellsec.rabbitmq;


import com.njupt.sellsec.domain.OrderInfo;
import com.njupt.sellsec.domain.SecOrder;
import com.njupt.sellsec.domain.SecSellMessage;
import com.njupt.sellsec.domain.SellUser;
import com.njupt.sellsec.redis.RedisService;
import com.njupt.sellsec.result.CodeMsg;
import com.njupt.sellsec.result.Result;
import com.njupt.sellsec.service.GoodsService;
import com.njupt.sellsec.service.OrderService;
import com.njupt.sellsec.service.SecSellService;
import com.njupt.sellsec.service.SellUserService;
import com.njupt.sellsec.vo.GoodsFormVO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;



/**
 * @Author: XJL
 * @Description:
 * @Date: Create in 21:50 2018/7/31
 * @Modified By:
 **/
@Service
public class MQReceiver {

    @Autowired
    private GoodsService goodsService;
    @Autowired
    private SellUserService sellUserService;
    @Autowired
    private OrderService orderService;
    @Autowired
    private SecSellService secSellService;

    private static Logger logger =  LoggerFactory.getLogger(MQReceiver.class);
/*    @RabbitListener(queues = MQConfig.QUEUE_NAME)//表示需要监听该queue
    public void receive(String message){

        logger.info("receive message: "+message);
    }
    @RabbitListener(queues = MQConfig.TOPIC_QUEUE1)
    public void receiveTopic1(String message){
        logger.info("receive topic1 message:"+message);
    }

    @RabbitListener(queues = MQConfig.TOPIC_QUEUE2)
    public void receiveTopic2(String message){
        logger.info("receive topic2 message:"+message);
    }

    @RabbitListener(queues = MQConfig.HEAD_QUEUE)
    public void receiveHeader(byte[] message){
        logger.info("receive header message:"+new String(message));
    }*/

   @RabbitListener(queues = MQConfig.SECSELL_QUEUE)
   public void receiveSecSellMessage(String message){
       SecSellMessage msg = RedisService.stringToBean(message, SecSellMessage.class);
       logger.info("【消费者收到消息】,message={}"+msg );
       long goodsId = msg.getGoodsId();
       SellUser user = msg.getUser();
       GoodsFormVO goodsFormVO = goodsService.getGoodInfoById(goodsId);
       if (goodsFormVO.getStockCount()<0){
           return;
       }
       //判断是否重复下单
       SecOrder secOrder = orderService.getSecOrderByUserIdAndGoodsId(user.getId(),goodsId);
       if (secOrder!=null){
           return;
       }
       //减库存 ，下订单 ， 保存订单
       secSellService.secSell(user,goodsFormVO);

   }
}
